
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

import { Dispatch } from "redux";
import { setNow } from '../../actions/actionSyncDemo';

export interface IHomePageProps {
  home: string;
  setNow: any;
  now: string;
}
export interface IHomePageState {
  timer: any;
}


class SyncDemo extends React.Component<IHomePageProps, IHomePageState> {
  constructor(props: IHomePageProps) {
    super(props);

    this.state = {
      timer: "",
    };
  }

  componentDidMount = () => {
    const timer = setInterval(() => {
      this.props.setNow();
    }, 30)

    this.setState({
      timer
    })
  }
  componentWillUnmount = () => {
    if (this.state.timer) {
      clearInterval(this.state.timer);

      this.setState({
        timer: ''
      })
    }
  }

  render() {
    const props = this.props;

    return (<div>
      <div>现在时间：{props.now}</div>
    </div>);
  }
}

export interface IStoreState {
  syncState: any;
}

const mapStateToProps = (state: IStoreState) => state.syncState;

//第一种方式
const mapDispatchToProps_1 = (dispatch: Dispatch) => {
  return {
    setNow: () => {
      setNow()(dispatch);//同步
    },
  }
};


//第二种方式
const mapDispatchToProps_2 = (dispatch: Dispatch) => {
  return bindActionCreators({
    setNow: () => {
      setNow()(dispatch);//同步
      return {
        type: ''
      };
    },
  }, dispatch);
}

const mapDispatchToProps = mapDispatchToProps_2;

export default connect(mapStateToProps, mapDispatchToProps)(SyncDemo);
